import random
import utils

class Manager:
    def __init__(self,game,config=None):
        self.game=game

        self.config=config
        self.lotterySum=self.config.data.initLotterySum
        self.passby={}
        self.lotteryPool={}

    def setMap(self,gameMap):
        self.gameMap=gameMap

    def regPassby(self,position,name,action):
        self.passby[position] = (name,action)

    def unregPassby(self,position):
        del self.passby[position]

    def move(self,player,step):
        now=player.pos

        isBreak=False
        breakPoint=-1
        for (pos,event) in sorted(self.passby.items()) :
            action=event[1]
            if now.inRange(pos,step):
                breakPoint,isBreak = pos,action(player)

        player.pos=now+step if not isBreak else breakPoint
        player.stop(self.gameMap[player.pos])

    def viewMap(self,player):
        self.gameMap.show(player)
        
    def viewInitMap(self,player):
        self.gameMap.showOrignal()

    def item(self,player):
        choice = player.invChoice()
        if choice==-1:
            return

        card=self.game.cardList[choice](self,player)
        if card.run():
            player.inv[choice]-=1

    def warning(self,player):
        res=[]
        now=player.pos

        for (pos,event) in self.passby.iteritems() :
            name=event[0]
            if now.inRange(pos,10*player.dir_,True):
                res.append((pos-now,name))

        self.game.showTable(res,title="Warning:\nPosition Type")

    def view(self,player):
        pos = self.game.getInput(
                prompt="Positive for front, negtive for behind. Please input an integer. Return to go back.",
                check=lambda x: not x or x.isalnum(),
                ) or None

        if pos is None:
            return
        pos=int(pos)

        self.game.showText(self.gameMap[player.pos+pos].profile())

    def profile(self,player):
        
        self.game.showTable(
            ( player.profile() for player in self.game.players ),
            title="Name cash saving points estate",
            )


    def toss(self,player):
        import pdb;pdb.set_trace()
        step=player.toss()*player.dir_
        self.move(player,step)

    def lose(self,player):
        self.game.lose(player)

    def lotteryShow(self):
        self.game.showText("Now the lottery of {} opens.".format(self.game.date.month))
        
        if getattr(self,'lotteryCheat',0):
            res=self.lotteryCheat
            self.lotteryCheat=0
        else:
            res=random.randint(1,20)

        self.game.showText("It takes... the {}!".format(res))

        if res in self.lotteryPool and self.lotteryPool[res] not in self.game.lost:
            player=self.lotteryPool[res]

            award=self.lotterySum / 2
            player.cash+=award
            self.lotterySum-=awrad
            self.lotteryPool={}

            self.game.showText("And the winner {} is awarded with cash ${}.".format(player,award))
        else:
            self.game.showText("Oops, no one has the poll {}, so the award will stay.".format(res))

        self.lotterySum+=int(self.lotterySum*self.config.data.interest)
        self.game.showText("Now the pool has {} in total.".format(self.lotterySum))

    def savingInterest(self):
        for player in self.game.players:
            player.saving+=int(player.saving*self.config.data.interest)

        self.game.showText("Everyone gets the interest from the bank for month {}.".format(self.game.date.month))

    def randomCard(self):
        res=None

        while res is None or self.game.cardList[res] is None:
            res = utils.probRandom(self.config.cardRate)

        return res

    def showPool(self,p):
        self.game.showText("The pool is as following:")
        for poll,player in sorted(self.lotteryPool.items()):
            self.game.showText("{} owned by {}".format(poll,player))

